<?php
namespace app\food\controller;

use think\Controller;
use think\Db;
use app\food\model\FoodModel;

class Apis extends Controller
{
    public function addFood($type, $name, $price, $detail, $note)
    {
        $food['type_id'] = $type;
        $food['food_name'] = $name;
        $food['food_price'] = $price;
        $food['food_detail'] = $detail;
        $food['food_sold'] = 0;
        $food['food_ctime'] = date('Y-m-d H:i:s', time());
        $food['food_note'] = $note;
        $FoodModel = new FoodModel();

        // 获取表单上传文件 例如上传了001.jpg
        $file = request()->file('image');
        // 移动到框架应用根目录/public/uploads/ 目录下
        $info = $file->validate(['size'=>10 * 1024 * 1024,'ext'=>'jpg,jpeg,png,gif,bmp'])->move(ROOT_PATH . 'public' . DS . 'uploads');
        if($info){  //存储路径
            $save =  $info->getSaveName();
//            $savePath = 'http://waimai.zhuantou.tv'.'/uploads/'.$save;
            $savePath = '/uploads/'.$save;
            $savePath = str_replace('\\', '/', $savePath);
            $food['food_pic'] = $savePath;
            $res = $FoodModel->addFood($food);

            //生成缩略图
            $realPath = $info->getRealPath();
            $image = \think\Image::open($realPath);
            $image->thumb(500, 500)->save($realPath);
        }else{
            // 上传失败获取错误信息
            $res = $file->getError();
        }
        return json($res);
    }

    public function delFoodById($id)
    {
        $FoodModel = new FoodModel();
        $res = $FoodModel->delFood($id);
        return json($res);
    }

    public function upFoodById($id, $type, $name, $price, $detail, $note)
    {
        $food['food_id'] = $id;
        $food['type_id'] = $type;
        $food['food_name'] = $name;
        $food['food_price'] = $price;
        $food['food_detail'] = $detail;
        $food['food_utime'] = date('Y-m-d H:i:s', time());
        $food['food_note'] = $note;
        $FoodModel = new FoodModel();

        // 获取表单上传文件 例如上传了001.jpg
        $file = request()->file('image');
        // 移动到框架应用根目录/public/uploads/ 目录下
        $info = $file->validate(['size'=>10 * 1024 * 1024,'ext'=>'jpg,jpeg,png,gif,bmp'])->move(ROOT_PATH . 'public' . DS . 'uploads');
        if($info){  //存储路径
            $save =  $info->getSaveName();
//            $savePath = 'http://waimai.zhuantou.tv'.'/uploads/'.$save;
            $savePath = '/uploads/'.$save;
            $savePath = str_replace('\\', '/', $savePath);
            $food['food_pic'] = $savePath;
            $res = $FoodModel->upFood($food);

            //生成缩略图
            $realPath = $info->getRealPath();
            $image = \think\Image::open($realPath);
            $image->thumb(500, 500)->save($realPath);
        }else{
            // 上传失败获取错误信息
            $res = $file->getError();
        }
        return json($res);
    }

    public function getAllFood()
    {
        $FoodModel = new FoodModel();
        $res = $FoodModel->getFood(null);
        return json($res);
    }

}
